/**
 * 搜索：刷新bootstrap-table
 * @param table
 */
function search(table) {
    table = table || $('#dataTable')
    table.bootstrapTable('refresh')
}

/**
 * 重置form
 * @param form
 */
function reset(form) {
    form = form || $("#searchForm")
    form[0].reset()
}

/**
 * 初始bootstrap-table
 * @param columns
 * @param form
 * @param table
 */
function initTable(columns, url, form, table) {
    url = url||requestPath.query
    form = form || $("#searchForm")
    table = table || $('#dataTable')
    table.bootstrapTable({
        url: url,
        method: "get",//请求方式  POST后台拿不到参数
        dataType: "json",//返回数据类型
        search: false,//是否显示表格搜索，此搜索是客户端搜索，不会进服务端
        //showRefresh: true,//刷新按钮
        //showColumns: true,//列选择按钮
        pagination: true,//是否显示分页（*）
        toolbar: '#toolbar',//指定工具栏
        toolbarAlign: "left",//工具栏对齐方式
        striped: true,//是否显示行间隔色
        cache: false,//是否使用缓存，默认为true
        sortable: true,//是否启用排序
        //传递参数
        queryParams: function (params) {
            let formParams = formToObj(form);
            console.log(formParams)
            return Object.assign(formParams,{
                size: params.limit,   //每页数量
                current: params.offset / params.limit + 1,
            })
        },
        //导入数据之前,设置复选框选中
        responseHandler: function (res) {
            // bootstrapTableShiroExpire(res);
            res.rows.forEach(function (row) {
                row.select = $.inArray(row.id, res.selectedIds) !== -1;
            })
            return res;
        },
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页（*）
        pageSize: 10,//每页的记录行数（*）
        pageList: [10, 20, 50, 100],//可供选择的每页的行数（*）
        minimumCountColumns: 2,//最少允许的列数
        clickToSelect: true,//是否启用点击选中行
        //showExport: true,//是否显示导出 需要tableExport和bootstrap-table-export
        exportDataType: "basic",//导出类型 'basic', 'all', 'selected'.
        uniqueId: "id",  //每一行的唯一标识，一般为主键列
        singleSelect: true,//是否单选
        smartDisplay: false,//显示每页显示条记录
        columns: columns,
        //没有匹配的结果
        formatNoMatches: function () {
            return "无符合条件的记录"
        },
        //导入错误
        onLoadError: function (data) {
            table.bootstrapTable('removeAll');
        }
    })
}

/**
 * 跳转新增
 * @param url
 */
function add(url) {
    url = url || requestPath.edit
    window.location.href = url
}

/**
 * 跳转编辑
 * @param table
 * @param url
 */
function edit(table, url) {
    table = table || $('#dataTable')
    url = url || requestPath.edit
    if (validCheckOne(table)) {
        let id = getSelectedId(table);
        window.location.href = url+'?id='+id
    }
}

/**
 * 删除
 * @param table
 */
function del(table, url) {
    table = table || $('#dataTable')
    url = url || requestPath.del
    if (validCheck(table)) {
        let ids = getSelectedIds(table);
        delById(url, ids.join(','));
    }
}

function delById(url, id) {
    url = url || requestPath.del
    id = id || $("#id").val()
    swal({
            title: "您确定要删除吗?",
            text: "删除后将无法恢复,请谨慎操作!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            closeOnConfirm: false
        }, function () {
            $.ajax({
                type: "get",
                url: url,
                data: "id=" + id,
                dataType: "json",
                success: function (info) {
                    let success= info.success
                    let message= info.message
                    swal(message)
                    if (success) {
                        setTimeout(function () {
                            location.href = requestPath.index
                        }, 1000);
                    }
                }
            })
        }
    )
}

/**
 * bootstrap-table工具
 * 校验是否选择了数据
 * @param table
 */
function validCheck(table) {
    table = table || $('#dataTable')
    let selections = getSelectedIds(table)
    if (selections.length == 0) {
        swal("请选择数据!")
        return false
    }
    return true
}

/**
 * bootstrap-table工具
 * 校验是否进行了单选
 * @param table
 */
function validCheckOne(table) {
    table = table || $('#dataTable')
    let selections = getSelectedIds(table)
    if (selections.length == 0) {
        swal("请选择一条数据!")
        return false
    } else if (selections.length > 1) {
        swal("只能选择一条数据!")
        return false
    }
    return true;
}

/**
 * bootstrap-table工具
 * 多选获取ID数组
 * @param table
 * @returns {*}
 */
function getSelectedIds(table) {
    table = table || $('#dataTable')
    return table.bootstrapTable('getSelections').map(function (item) {
        return item.id
    })
}

/**
 * bootstrap-table工具
 * 单选获取ID
 * @param table
 * @returns {*}
 */
function getSelectedId(table) {
    table = table || $('#dataTable')
    return table.bootstrapTable('getSelections')[0].id
}


function saveData(url, form) {
    url = url || requestPath.save
    form = form || $("#editFrom")
    if (form.valid()) {
        $.ajax({
            type: "post",
            url: url,
            data: formToObj(form),
            dataType: "json",
            success: function (info) {
                let success= info.success
                let message= info.message
                swal(message)
                if (success) {
                    setTimeout(function () {
                        back()
                    }, 1000)
                }
            }
        })
    }
}

/**
 * 表单转对象
 */
function formToObj(form) {
    form = form||$("#editFrom")
    let data = {}
    form.serializeArray().forEach(function (item) {
        if (item.value) {
            data[item.name] = item.value
        }
    })
    return data
}

/**
 * 跳转到指定路径
 * @param url
 */
function back(url) {
    url = url||requestPath.index
    window.location.href = url
}


/**
 * 树结构初始化
 * @param enableCheck 可选择树
 * @param loadData 点击后加载表单数据
 * @param treeList 树数据
 * @param url 请求表单数据路径
 * @param tree 树元素默认id为tree的
 */
function initTree(enableCheck, loadData, treeList, url, tree) {
    tree = tree||$("#tree")
    let setting = {
        check: {
            enable: enableCheck,
            chkStyle: "radio",
            radioType: "all"
        },
        view: {
            dblClickExpand: false,
            showLine: true,
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootPId: ""
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
                $.ajax({
                    type: "get",
                    url: url+'/'+treeNode.id,
                    data: '',
                    dataType: "json",
                    success: function (data) {
                        if (data && data.success === true) {
                            $("#id").val(data.info.id)
                            $("#parentId").val(data.info.parentId)
                            if (treeNode.getParentNode()) {
                                $("#parentName").val(treeNode.getParentNode().name)
                            } else {
                                $("#parentName").val("root")
                            }
                            $(".btn-danger").show()//显示删除按钮
                            loadData(data.info)
                        } else {
                            swal(data.message)
                        }
                    }
                })
            }
        }
    }
    $.fn.zTree.init(tree, setting, treeList)
}

function addTree(treeId) {
    treeId = treeId||"tree"
    //屏蔽删除按钮
    $(".btn-danger").hide()
    let treeObj = $.fn.zTree.getZTreeObj(treeId)
    let selectedNodes = treeObj.getSelectedNodes()
    //重置表单数据
    $('#editFrom')[0].reset()
    $("#id").val("")
    if (selectedNodes) {
        $("#parentId").val(selectedNodes[0].id);
        $("#parentName").val(selectedNodes[0].name);
    } else {
        $("#parentId").val("0")
        $("#parentName").val("root")
    }
}

function saveTree(url, form) {
    url = url||requestPath.save
    form = form||$("#editFrom")
    if (form.valid()) {
        $.ajax({
            type: "post",
            url: url,
            data: formToObj(form),
            dataType: "json",
            success: function (info) {
                let success= info.success
                let message= info.message
                swal(message)
                if (success) {
                    setTimeout(function () {
                        location.href = requestPath.index
                    }, 1000);
                }
            }
        })
    }
}


/**
 * TODO 下拉框开始:场站、通道
 */
$(function () {
    //提示框
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "1000",
        "timeOut": "1000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }
    /**
     * 关区下拉添加change方法
     */
    if ($("#cusCode").length && ($("#staCode").length || $("#staCodeUser").length)) {
        let child = $("#staCode").length ? $("#staCode") : $("#staCodeUser")
        let url = $("#staCode").length ? parent.api.bus.sta.select : parent.api.bus.sta.selectByUser
        $("#cusCode").change(function () {
            let cusCode = $("#cusCode").val()
            fillSelect({cusCode:cusCode}, url, child)
            if ($("#passCode").length || $("#passCodeEnable").length) {
                $("#passCode").length ? $("#passCode").find("option:not(:first)").remove() : $("#passCodeEnable").find("option:not(:first)").remove()
            }
        })
    }
    /**
     * 场站下拉添加change方法
     */
    if (($("#passCode").length || $("#passCodeEnable").length) && ($("#staCode").length || $("#staCodeUser").length)) {
        let current = $("#staCode").length ? $("#staCode") : $("#staCodeUser")
        let child = $("#passCode").length ? $("#passCode") : $("#passCodeEnable")
        let url = $("#passCode").length ? parent.api.bus.pass.select : parent.api.bus.pass.selectEnable
        current.change(function () {
            let staCode = current.val()
            fillSelect({staCode:staCode}, url, child)
        });
    }
})

function fillSelect(data, url, current, selectedVal) {
    current.find("option:not(:first)").remove()// document.getElementById("staCode").length = 1
    if (Object.values(data) && Object.values(data)[0]) {
        $.ajax({
            type: "get",
            url: url,
            data: data,
            dataType: "json",
            success: function (data) {
                if (data.success == true) {
                    for (let i = 0; i < data.info.length; i++) {
                        let item = data.info[i]
                        current.append("<option value='"+item.code+"' "+(item.code == selectedVal ? 'selected' : '')+">"+item.name+"</option>")
                    }
                }
            }
        })
    }
}

let checkSubmitFlg = false;

function checkSubmit() {
    if (!checkSubmitFlg) {
        //第一次提交
        checkSubmitFlg = true;
        return true;
    } else {
        //重复提交
        swal("数据正在传送中，请勿重复提交！");
        return false;
    }
}
